import { snapshot } from 'valtio'
import axios, { AxiosError, type AxiosResponse } from 'axios'

import { API_URL } from '@/constants'
import { userState } from '@/stores'

export const instance = axios.create({
  baseURL: API_URL,
})

instance.interceptors.request.use((config) => {
  const snap = snapshot(userState)
  config.headers.openId = snap.openid ?? ''
  config.headers.signValue = '0e51fccba5fc1be3139739df624ae3cf-wxApp'
  return config
})

export function unwrap<R = Data>(res: AxiosResponse<API.Res<R>>) {
  if (res.status >= 200 && res.status <= 300) {
    if (res.data.code === '1') {
      return res.data.data
    }
  }

  const code = res.data?.code ?? res.status
  const msg = res.data?.msg ?? res.statusText

  throw new AxiosError(msg, String(code), res.config, res.request, res)
}
